<template>
	<div class="">
		<activity-ad-swiper :type="AdPositionType.login" />
		<div class="h-group-t-big"></div>
		<div class="flex justify-between gap-5 rounded-lg p-[10px] h-[68px] bg-bg-1 overflow-x-auto">
			<base-switch-tabs
				:modelValue="tab"
				@update:modelValueAll="handleChangeTab"
				:data="tabList"
				size="large"
				:translation="false"
				:isUseLocalIcon="false"
				activeTextBold />
			<div
				v-if="isPC()"
				class="flex items-center rounded-lg border border-border-1 bg-bg-3 app-bg-react w-100 px-[10px] flex-1 text-t-3 max-w-[511px] whitespace-nowrap"
				@click="searchClick">
				<base-icon class="text-[20px] flex-shrink-0 mr-[5px]" name="search"></base-icon>
				<div>{{ t('action.search') }}</div>
			</div>
		</div>
		<div class="h-group-t-xl"></div>
		<template v-if="tab === 'lobby'">
			<base-loading-box :isEmpty="isEmpty" :loading="loading">
				<GameList type="playerRecent" />

				<div class="h-group-t-xl"></div>
				<home-all />
			</base-loading-box>
		</template>
		<template v-else>
			<base-loading-box :isEmpty="isEmpty" :loading="loading">
				<router-link :to="handleRouterLink()" class="text-primary no-underline">
					<card-title
						:iconColor="'var(--color-primary)'"
						:isUseLocalIcon="false"
						:size="20"
						:img="gameList.labelIcon"
						:text="gameList.labelName" />
				</router-link>
				<n-grid
					ref="el"
					:y-gap="isDesktop ? 10 : 16"
					:x-gap="isDesktop ? 12 : 8.5"
					:cols="colsTags">
					<n-gi v-for="(item, index) in gameList.games" :key="index" class="app-hover-offset">
						<item-card :item="item" />
					</n-gi>
				</n-grid>
				<div class="text-center mt-[20px] mb-[10px]">
					<router-link :to="handleRouterLink()" class="text-primary no-underline">
						{{ $t('app.viewAll') }} {{ gameList.totalItems }} {{ gameList.labelName }}
					</router-link>
				</div>
			</base-loading-box>
			<div class="h-group-t-xl"></div>
			<GameList type="provider" />
		</template>

		<div class="h-group-t-xl"></div>
		<home-live />
	</div>
</template>
<script lang="ts" setup>
import { onMounted, ref, Ref } from 'vue'

import { NGi, NGrid } from 'naive-ui'
import { BaseIcon, BaseSwitchTabs, SwitchTabsItem, BaseLoadingBox } from '@/components/base'
import HomeLive from './home-live.vue'
import GameList from '@/components/slots/game-list/index.vue'
import ItemCard from '@/components/slots/common/item-card.vue'
import CardTitle from '@/components/slots/common/card-title.vue'
import HomeAll from './home-all.vue'
import { ActivityAdSwiper } from '@/components/activity'
import { AdPositionType } from '@/enums'
import { bus, isPC, t } from '@/utils'
import { useAppStore, useCasinoStore, useSearchGameStore } from '@/store'
import { useListCols, useRequest } from '@/hooks'
import { gameRecentPlayedList, getCasinoGameBySlug, getGameTagList } from '@/api/other'
import { isDesktop } from '@/hooks/useIsPC.ts'
import { useRoute, useRouter } from 'vue-router'
import { find } from 'lodash-es'

const route = useRoute()
const router = useRouter()
const casinoStore = useCasinoStore()
const appStore = useAppStore()
const searchGameStore = useSearchGameStore()
const loading = ref(false)
const isEmpty = ref(true)
const tab = ref<string | number>('')
const el = ref(null)
const tabList = ref<SwitchTabsItem[]>([])
const gameList: Ref<any> = ref({
	gameTagGroupId: '1',
	id: '1',
	games: []
})
const { colsTags } = useListCols(el)
const { run, data } = useRequest<any>(getGameTagList)
const { run: getCasinoGameBySlugData, data: dataById } = useRequest<any>(getCasinoGameBySlug)
const { run: getRecentPlayerData, data: recentPlayerData } = useRequest<any>(gameRecentPlayedList)

onMounted(() => {
	getData()
})

bus.$on('LANG_EVENT', () => {
	getData()
})
const getData = async () => {
	loading.value = true
	isEmpty.value = true
	searchGameStore.hide()
	tabList.value = casinoStore.lobbyTabList
	await run({ displayLocation: 'CASINO_LOBBY_UPPER_TAG_DISPLAY' })
	tabList.value = data.value

	let formatArray = <SwitchTabsItem[]>[
		{
			id: 'lobby',
			name: '',
			nameT: 'casinoAll.lobby',
			icon: 'https://d11njdywhf5zo.cloudfront.net/test-2up/2024/10/11/00f46f3e0bf94bfdb7e81ef15ae036b0.svg'
		},
		{
			id: 'recent',
			name: '',
			nameT: 'casinoAll.recent',
			icon: 'https://d11njdywhf5zo.cloudfront.net/test-2up/2024/10/24/17ca6790a1f843a9bbd30779e97a03d9.svg'
		}
	]
	for (let i = 0; i < tabList.value.length; i++) {
		if (data.value[i]) {
			let obj = {
				id: data.value[i].tagSlug,
				name: data.value[i].labelName,
				icon: data.value[i].labelIcon
			}
			formatArray.push(obj)
		}
	}
	tabList.value = formatArray
	casinoStore.setLobbyTabList(tabList.value)
	if (route.name === 'casino') {
		tab.value = 'lobby'
		setTimeout(() => {
			isEmpty.value = false
			loading.value = false
		}, 1000)
	} else if (route.params.id === 'recent') {
		tab.value = route.params.id as string
		await getRecentPlayerData({
			page: 1,
			pageSize: 24
		})
		gameList.value = recentPlayerData.value
		gameList.value.games = recentPlayerData.value.items
		gameList.value.labelName = t('casinoAll.recent')
		gameList.value.labelIcon =
			'https://d11njdywhf5zo.cloudfront.net/test-2up/2024/10/24/17ca6790a1f843a9bbd30779e97a03d9.svg'

		if (gameList.value.games.length > 0) {
			isEmpty.value = false
		} else {
			isEmpty.value = true
		}
	} else {
		// FIX 不同语言配置的游戏标签id不一样, 切换语言时如果 使用地址栏旧语言的 params.id (tagSlug)查询会空数据
		const current = <SwitchTabsItem | null>find(tabList.value, { id: route.params.id })
		if (current && route.params.id === current?.id) {
			tab.value = current.id
		} else {
			tab.value = current?.id || tabList.value[0].id
			await router.push(`/${appStore.lang}/casino/home/${tab.value}`)
		}
		await getCasinoGameBySlugData({ page: 1, pageSize: 24, tagSlug: tab.value })
		dataById.value[0] && (gameList.value = dataById.value[0])
		if (gameList.value.games.length > 0) {
			isEmpty.value = false
		} else {
			isEmpty.value = true
		}
	}

	loading.value = false
}

const handleChangeTab = async (val: any) => {
	tab.value = val.id
	loading.value = true
	isEmpty.value = true
	if (val.id === 'recent') {
		router.push(`/${appStore.lang}/casino/home/recent`)
		await getRecentPlayerData({
			page: 1,
			pageSize: 24
		})
		gameList.value = recentPlayerData.value
		gameList.value.games = recentPlayerData.value.items
		gameList.value.labelName = t('casinoAll.recent')
		gameList.value.labelIcon =
			'https://d11njdywhf5zo.cloudfront.net/test-2up/2024/10/24/17ca6790a1f843a9bbd30779e97a03d9.svg'

		if (gameList.value.games.length > 0) {
			isEmpty.value = false
		} else {
			isEmpty.value = true
		}
		loading.value = false
	} else if (val.id !== 'lobby') {
		router.push(`/${appStore.lang}/casino/home/${val.id}`)

		await getCasinoGameBySlugData({ page: 1, pageSize: 24, tagSlug: val.id, sort: 1 })
		dataById.value[0] && (gameList.value = dataById.value[0])

		if (gameList.value.games.length > 0) {
			isEmpty.value = false
		} else {
			isEmpty.value = true
		}
		loading.value = false
	} else {
		router.push(`/${appStore.lang}/casino/home`)
		setTimeout(() => {
			isEmpty.value = false
			loading.value = false
		}, 1000)
	}
}
const searchClick = () => {
	searchGameStore.show()
}
const handleRouterLink = () => {
	if (route.params.id === 'recent') {
		return {
			name: 'recent'
		}
	} else {
		return {
			name: 'casinoTags',
			params: {
				locale: appStore.lang,
				id: gameList.value.tagSlug || '1'
			}
		}
	}
}
</script>
